﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.BLL;
using MxWeiXinPF.WeiXinComm;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using Senparc.Weixin.MP.AdvancedAPIs.Media;
using System.Text.RegularExpressions;

namespace MxWeiXinPF.Web.admin.crm
{
    public partial class qunfa : Web.UI.ManagePage
    {
        wx_requestRule rBll = new wx_requestRule();
        wx_requestRuleContent rcBll = new wx_requestRuleContent();
        protected int channel_id = 16;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ShowInfo();

            }
        }

        #region 赋值操作=================================
        private void ShowInfo()
        {
            Model.wx_userweixin weixin = GetWeiXinCode();
            //显示组别
            BLL.wx_crm_group groupBll = new wx_crm_group();
            IList<Model.wx_crm_group> gList = groupBll.GetModelList("wid=" + weixin.id);

            this.cblGroup.Items.Clear();
            this.cblGroup.Items.Add(new ListItem("所有人", ""));
            if (gList != null && gList.Count >= 0)
            {
                foreach (Model.wx_crm_group group in gList)
                {
                    this.cblGroup.Items.Add(new ListItem(group.name, group.groupid.ToString()));
                }
            }
            this.cblGroup.SelectedIndex = 0;


        }
        #endregion


        /// <summary>
        /// 预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnYuLan_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("qunfa_weixin", MXEnums.ActionEnum.Edit.ToString()); //检查权限
              Model.wx_userweixin weixin = GetWeiXinCode();
         
            BLL.wx_property_info propertyBll = new wx_property_info();
            Model.wx_property_info propertyEntity = propertyBll.GetModelByIName(weixin.id, MXEnums.WXPropertyKeyName.YuLanOpenid.ToString());
            if (propertyEntity == null || string.IsNullOrEmpty( propertyEntity.iContent)  )
            {
                JscriptMsg("尚未设置预览的用户，请先设置预览用户的openid！", "yulanOpenid.aspx");
                return;
            }
            QunFaFun(0, propertyEntity.iContent);
        }


        /// <summary>
        /// 群发按钮
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("qunfa_weixin", MXEnums.ActionEnum.Edit.ToString()); //检查权限
            QunFaFun(1,"");
           
        }



        /// <summary>
        /// 群发的主方法
        /// </summary>
        /// <param name="actionType">0为预览，1为真实的群发</param>
        private void QunFaFun(int actionType,string yulanOpenid)
        {
            try
            {

                Model.wx_userweixin weixin = GetWeiXinCode();

                //群发内容类型 GroupMessageType
                int ResponseType = MyCommFun.Str2Int(rblResponseType.SelectedItem.Value,1);
                string textContent = txtContent.Text.Trim();

                string err = "";
                string AccessToken = WeiXinCRMComm.getAccessToken(weixin.id, out  err);
                bool isToAll = false;
                int groupId = -1;
                if (cblGroup.Items[0].Selected)
                {
                    isToAll = true;
                }
                else
                {
                    groupId = MyCommFun.Str2Int(cblGroup.SelectedItem.Value);
                }

                if (ResponseType == 1)
                {
                    #region 纯文本的群发 
                    if (actionType == 0)
                    {
                        //预览 	
                        GroupMessageApi.SendGroupMessagePreview(AccessToken, GroupMessageType.text, textContent, yulanOpenid);
                    }
                    else
                    {
                        //群发文本
                        GroupMessageApi.SendGroupMessageByGroupId(AccessToken, groupId.ToString(), textContent, (GroupMessageType)ResponseType, isToAll);
                       
                        //记录到群发历史表里 start
                        Model.wx_qunfa_history qfh = new Model.wx_qunfa_history();
                        qfh.wid = weixin.id;
                        qfh.MessageType = GroupMessageType.text.ToString();
                        qfh.sendStyle = isToAll ? 3 : 1;
                        qfh.mValue = textContent;
                        qfh.mStatus = 1;
                        qfh.createDate = DateTime.Now;
                        qfh.groupName = cblGroup.SelectedItem.Text;
                        BLL.wx_qunfa_history qfhBll = new wx_qunfa_history();
                        qfhBll.Add(qfh);
                        //记录到群发历史表里 end
                       
                    }

                    #endregion


                }
                else
                {
                    #region 群发图文
                    int categoryId = MyCommFun.Str2Int(hidCategoryId.Value);
                    UploadNews(actionType, AccessToken, categoryId, weixin.id, groupId.ToString(), isToAll, yulanOpenid);
                    #endregion


                }

                AddAdminLog(MXEnums.ActionEnum.Edit.ToString(), "群发操作成功。"); //记录日志
                JscriptMsg("发送成功！", "qunfa.aspx");
            }
            catch (Exception ex)
            {
                AddAdminLog(MXEnums.ActionEnum.Edit.ToString(), "群发成功有问题,ex"+ex.Message); //记录日志
                JscriptMsg("群发成功有问题！", "qunfa.aspx");
            }
        
        }


       
        /// <summary>
        /// 群发图文素材
        /// </summary>
        /// <param name="actionType">为预览，1为真实的群发</param>
        /// <param name="AccessToken"></param>
        /// <param name="categoryId"></param>
        /// <param name="wid"></param>
        /// <param name="groupId"></param>
        /// <param name="isToAll"></param>
        /// <param name="yulanOpenid">预览的用户openid</param>
        private void UploadNews(int actionType, string AccessToken, int categoryId, int wid, string groupId, bool isToAll, string yulanOpenid)
        {
            //获取图文的内容
            BLL.article articleBll = new BLL.article();

            DataSet articleDS = articleBll.GetList(" channel_id=" + channel_id + " and category_id=" + categoryId + " and wid=" + wid + " order by  sort_id asc");

            if (articleDS == null || articleDS.Tables.Count <= 0 || articleDS.Tables[0].Rows.Count <= 0)
            {
                return;
            }
            int length = articleDS.Tables[0].Rows.Count;
            NewsModel[] newsArr = new NewsModel[length];

            DataRow dr;
            NewsModel newsModel = new NewsModel();
            string titleStr = "";
            for (int i = 0; i < length; i++)
            {
                dr = articleDS.Tables[0].Rows[i];
                newsModel = new NewsModel();
                newsModel.title = dr["title"].ToString();//标题
                newsModel.author = dr["user_name"].ToString();//作者
                newsModel.digest = dr["zhaiyao"].ToString();//摘要
                newsModel.content = ProcContentImg(AccessToken, dr["content"].ToString());//内容
                newsModel.show_cover_pic = "0";//封面是否显示，0为不显示，1为显示
                newsModel.content_source_url = dr["link_url"].ToString();//在图文消息页面点击“阅读原文”后的页面
                //图文封面的缩略图
                //newsModel.thumb_media_id = MediaApi.UploadForeverMedia(AccessToken, Server.MapPath(dr["img_url"].ToString())).media_id;//永久素材
                newsModel.thumb_media_id = MediaApi.UploadTemporaryMedia(AccessToken, UploadMediaFileType.image, Server.MapPath(dr["img_url"].ToString())).media_id;
                newsArr[i] = newsModel;
                titleStr +="||"+ newsModel.title;
            }
            //上传临时的图文素材
            UploadTemporaryMediaResult utmr = MediaApi.UploadTemporaryNews(AccessToken, 10000, newsArr);
            if (actionType == 0)
            {
                //预览 	
                GroupMessageApi.SendGroupMessagePreview(AccessToken, GroupMessageType.mpnews, utmr.media_id, yulanOpenid);
            }
            else
            {  //发送
                GroupMessageApi.SendGroupMessageByGroupId(AccessToken, groupId, utmr.media_id, GroupMessageType.mpnews, isToAll);

                //记录到群发历史表里 start
                Model.wx_qunfa_history qfh = new Model.wx_qunfa_history();
                qfh.wid = wid;
                qfh.MessageType = GroupMessageType.mpnews.ToString();
                qfh.sendStyle = isToAll ? 3 : 1;
                qfh.mValue = titleStr;
                qfh.mStatus = 1;
                qfh.groupName = cblGroup.SelectedItem.Text;
                qfh.createDate = DateTime.Now;

                BLL.wx_qunfa_history qfhBll = new wx_qunfa_history();
                qfhBll.Add(qfh);
                //记录到群发历史表里 end

            }
          
          
            
        }

        /// <summary>
        /// 处理图文的文章里的图片
        /// </summary>
        /// <param name="AccessToken"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private string ProcContentImg(string AccessToken, string content)
        {
            string ret = content;

            string[] imgArr = GetHtmlImageUrlList(content);
            if (imgArr == null || imgArr.Length <= 0)
            {
                return content;
            }
            UploadImgResult uir;
            string newUri = "";
            for (int i = 0; i < imgArr.Length; i++)
            {
                try
                {

                    uir = MediaApi.UploadImg(AccessToken, Server.MapPath(imgArr[i].ToString()));
                    newUri = uir.url;
                    ret = ret.Replace(imgArr[i], newUri);

                }
                catch (Exception ex)
                {

                }


            }

            return ret;

        }


        #region 一些小方法
        /// <summary> 
        /// 取得HTML中所有图片的 URL。 
        /// </summary> 
        /// <param name="sHtmlText">HTML代码</param> 
        /// <returns>图片的URL列表</returns> 
        public string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签 
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串 
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表 
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }

        /// <summary>
        /// 一维string数组去掉去重算法
        /// </summary>
        /// <param name="needToPurge"></param>
        public void Purge(ref List<string> needToPurge)
        {

            for (int i = 0; i < needToPurge.Count - 1; i++)
            {
                string deststring = needToPurge[i];
                for (int j = i + 1; j < needToPurge.Count; j++)
                {
                    if (deststring.CompareTo(needToPurge[j]) == 0)
                    {
                        needToPurge.RemoveAt(j);
                        continue;
                    }
                }
            }
        }

        #endregion

    }
}